#include "comm.hpp"
#include "inetAddr.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc <<" server_ip server_port" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(SOCKET_ERR);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 发送建立连接的请求
    InetAddr serveraddr(server_ip, server_port);
    int n = connect(sockfd, serveraddr.NetAddrPtr(), serveraddr.NetAddrLen());
    if(n < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(CONNECT_ERR);
    }

    while(1)
    {
        std::string line;
        std::cout << "Please Enter: ";
        std::getline(std::cin, line);

        write(sockfd, line.c_str(), line.size());
        
        char buff[1024];
        ssize_t size = read(sockfd, buff, sizeof(buff));
        if(size > 0)
        {
            buff[size] = 0;
            std::cout << buff << std::endl;
        }
    }

    close(sockfd);

    return 0;
}